import React, { useCallback, useEffect, useState } from "react";
import {
  Space,
  Table,
  Tag,
  Button,
  Modal,
  Form,
  Input,
  Popconfirm,
} from "antd";
import type { TableProps } from "antd";
import { FormOutlined, DeleteOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import instance from "../../api/instance";

interface DataType {
  key: string;
  title: string;
  updatedAt: string;
  viewCount: number;
  tags: string[];
  id: number;
  content: string;
}

const Data: React.FC = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();

  const [tabelData, setTabelData] = useState<DataType[]>([]);
  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "文章标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
    },
    {
      title: "浏览次数",
      dataIndex: "viewCount",
      key: "viewCount",
    },
    {
      title: "内容",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "更新时间",
      dataIndex: "updatedAt",
      key: "updatedAt",
    },
    {
      title: "标签",
      key: "tags",
      dataIndex: "tags",
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            return <Tag key={tag.name}>{tag.name.toUpperCase()}</Tag>;
          })}
        </>
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button color="primary" variant="link">
            查看详情
          </Button>
          <FormOutlined
            onClick={() => {
              clickEdit(record);
            }}
          />
          <Popconfirm
            title="删除"
            description="是否确认删除？"
            onConfirm={() => confirmDelete(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <DeleteOutlined />
          </Popconfirm>
        </Space>
      ),
    },
  ];
  const [tabelTotal, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [title, setTitle] = useState("");
  const [tag, setTag] = useState("");
  const [searchForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [isEdit, setIsEdit] = useState(false);

  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [selectedKeys, setSelectedKeys] = useState<number[]>([])

  const loadTable = () => {
    // 手动处理参数字段
    const params: {
      page: number;
      pageSize: number;
      keyword?: string;
      tag?: string;
    } = { page, pageSize };

    //title和tag这两个字段，只有有值的时候才携带
    if (title) params.keyword = title;
    if (tag) params.tag = tag;

    instance.get("/article/list", { params }).then((res) => {
      if (res.data.rows) {
        setTabelData(res.data.rows);
        setTotal(res.data.count);
      }
    });
  };

  const clickEdit = (row) => {
    setIsEdit(true);
    setOpen(true);
    editForm.setFieldsValue(row);
  };

  // 点击查询按钮，同步修改 标题和标签字段
  const onSearch = (values) => {
    setTitle(values.title);
    setTag(values.tag);
  };

  // 重置搜索表单
  const resetSearch = () => {
    searchForm.resetFields();
    setTitle("");
    setTag("");
  };

  const confirmDelete = useCallback((id: number) => {
      const newData = tabelData.filter((t: DataType) => t.id !== id);
      setTabelData(newData);
    },
    [tabelData]
  );

  useEffect(() => {
    loadTable();
    loadTable();
    setTimeout(()=> {
        loadTable()
    }, 500)
  }, [page, pageSize, title, tag]);

  const pageChange = useCallback(
    (currentPage: number, currentPageSize: number) => {
      setPage(currentPage);
      setPageSize(currentPageSize);
    },
    []
  );

  const handleOk = () => {
    setConfirmLoading(true);
    const { content, title, id } = editForm.getFieldsValue();

    if (!isEdit) {
      // 新增
      instance
        .post("/article", {
          title,
          content,
          tagList: ["新增测试"],
          categoryList: ["测试分类"],
          authorId: "47529555",
        })
        .then((res) => {
          if (res.data.id) {
            setOpen(false);
            loadTable();
            setConfirmLoading(false);
            editForm.resetFields();
          }
        });
    } else {
      // 编辑
      instance
        .put(`/article/${id}`, {
          title,
          content,
          tagList: ["新增测试"],
          categoryList: ["测试分类"],
          authorId: "47529555",
        })
        .then((res) => {
          if (res.status === 204) {
            setOpen(false);
            loadTable();
            setConfirmLoading(false);
            editForm.resetFields();
          }
        });
    }
  };

  const handleCancel = () => {
    setOpen(false);
    editForm.resetFields();
    setIsEdit(false);
  };

  const rowSelecChange = (selectedRowKeys: number[]) => {
    setSelectedKeys(selectedRowKeys)
  };

  const deleteSome = () => {
    const newData = tabelData.filter((t: DataType) => !selectedKeys.includes(t.id));
    setTabelData(newData);
  }

  return (
    <div>
      <Form
        name="basic"
        layout="inline"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        onFinish={onSearch}
        form={searchForm}
      >
        <Form.Item label="标题" name="title">
          <Input />
        </Form.Item>

        <Form.Item label="标签" name="tag">
          <Input />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={resetSearch}>
            重置
          </Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
      </Form>

      <h1 style={{margin: '20px 0'}}>{t("data.title")}</h1>
      <Button type="primary" onClick={() => setOpen(true)}>
        新增
      </Button>
      <Button onClick={deleteSome} type="primary"> 批量删除 </Button>
      <Table<DataType>
        columns={columns}
        dataSource={tabelData}
        rowKey="id"
        pagination={{
          total: tabelTotal,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `总共 ${total} 条`,
          position: ["bottomCenter"],
          onChange: pageChange,
        }}
        rowSelection={{
          type: "checkbox",
          onChange: rowSelecChange,
        }}
      />
      <Modal
        title={isEdit ? "编辑" : "新增"}
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <Form
          name="edit"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          form={editForm}
        >
          {isEdit && (
            <Form.Item label="id" name="id">
              <Input disabled />
            </Form.Item>
          )}
          <Form.Item label="标题" name="title">
            <Input />
          </Form.Item>

          <Form.Item label="内容" name="content">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Data;
